package com.nowcoder.community.controller;

import com.google.code.kaptcha.Producer;
import com.nowcoder.community.annotation.LoginRequired;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.CommunityUtil;
import com.nowcoder.community.util.RedisKeyUtil;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller
public class LoginController implements CommunityConstant {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private Producer kaptchaProducer;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    /**
     * 返回注册页面
     * 由于我们使用了thymeleaf
     * 所以一个html页面中动态的数据都是通过Model注入(Model通过DispacherServlet进行实例化)
     * 而我们需要给前端返回的就是静态html页面所在的路径
     *
     * @return
     */
    @RequestMapping(path = "/register", method = RequestMethod.GET)
    public String getRegisterPage() {
        return "/site/register";
    }

    @RequestMapping(path = "/login", method = RequestMethod.GET)
    public String getLoginPage() {
        return "/site/login";
    }

    /**
     * User对象会被Spring MVC自动注入Model对象中
     * 在前端页面可以直接拿到
     *
     * @param model
     * @param user
     * @return
     */
    @RequestMapping(path = "/register", method = RequestMethod.POST)
    public String register(Model model, User user) {
        Map<String, Object> map = userService.register(user);
        // 注册成功
        if(map == null || map.isEmpty()) {
            model.addAttribute("msg", "注册成功!我们已经向您的邮箱发送了激活邮件");
            model.addAttribute("targetURL", "/index");
            return  "/site/operate-result";
        }
        // 注册失败
        else {
            model.addAttribute("usernameMsg", map.get("usernameMsg"));
            model.addAttribute("passwordMsg", map.get("passwordMsg"));
            model.addAttribute("emailMsg", map.get("emailMsg"));
            return "/site/register";
        }
    }

    @RequestMapping(path = "/activation/{userId}/{code}", method = RequestMethod.GET)
    public String activate(Model model, @PathVariable("userId") int userId, @PathVariable("code") String code) {
        int res = userService.activate(userId, code);
        // 激活成功
        if(res == ACTIVATION_SUCCESS) {
            model.addAttribute("msg", "激活成功!您的账号已经可以正常使用");
            // 目标跳转页面是登录页面
            model.addAttribute("targetURL", "/login");
        }
        else if(res == ACTIVATION_REPEAT) {
            model.addAttribute("msg", "激活无效!您的账号已经被激活啦");
            model.addAttribute("targetURL", "/index");
        }
        else {
            model.addAttribute("msg", "激活失败!您所提供的激活码不正确");
            model.addAttribute("targetURL", "/index");
        }
        return "/site/operate-result";
    }

    /**
     * 把验证码图片的路径存储在session中
     * 因为客户端是先请求一次验证码图片
     * 然后正式发送登录请求时，才把用户输入传到后端
     * 所以需要保存上一次请求生成的验证码图片，这就涉及到了跨请求信息
     * 而验证码又是一个敏感信息，所以应该用session保存在服务端，而不可以用cookie保存在客户端
     *
     * @param response
     */
    @RequestMapping(path = "/kaptcha", method = RequestMethod.GET)
    @ResponseBody
    public void getKaptchaImage(HttpServletResponse response /*HttpSession session*/) throws IOException {
        // 生成验证码
        String content = kaptchaProducer.createText();
        BufferedImage image = kaptchaProducer.createImage(content);

        // 将验证码存入session
        // session.setAttribute("content", content);

        // 先生成标识用户和验证码关系的字符串
        String kaptchaOwner = CommunityUtil.generateUUID();
        Cookie cookie = new Cookie("kaptchaOwner", kaptchaOwner);
        // 设置60s的有效期
        cookie.setMaxAge(60);
        cookie.setPath(contextPath);
        response.addCookie(cookie);

        // 将验证码存入Redis
        String kaptchaRedisKey = RedisKeyUtil.getKaptchaKey(kaptchaOwner);
        redisTemplate.opsForValue().set(kaptchaRedisKey, content, 60, TimeUnit.SECONDS);

        // 将图片输入到浏览器
        // 设置response信息的类型
        response.setContentType("image/png");
        try {
            OutputStream os = response.getOutputStream();
            ImageIO.write(image, "png", os);
        } catch(IOException e) {
            logger.error("响应验证码失败: " + e.getMessage());
        }
    }

    @RequestMapping(path = "/login", method = RequestMethod.POST)
    public String login(String username, String password, String code, boolean isRemembered,
                        Model model, /*HttpSession session,*/ HttpServletResponse response,
                        @CookieValue(value = "kaptchaOwner", required = false) String kaptchaOwner)
    {
        // 检查验证码是否正确
        // String rightCode = (String)session.getAttribute("content");

        // 从Redis中取验证码

        // 验证码过期
        if(StringUtils.isBlank(kaptchaOwner)) {
            model.addAttribute("codeMsg", "验证码已过期,请刷新!");
            return "/site/login";
        }
        String kaptchaRedisKey = RedisKeyUtil.getKaptchaKey(kaptchaOwner);
        String kaptcha = (String)redisTemplate.opsForValue().get(kaptchaRedisKey);

        // 再核实一下验证码是否过期
        if(StringUtils.isBlank(kaptcha)) {
            model.addAttribute("codeMsg", "验证码已过期,请刷新!");
            return "/site/login";
        }
        // 验证码输入错误
        else if(StringUtils.isBlank(code) || !kaptcha.equalsIgnoreCase(code)){
            model.addAttribute("codeMsg", "验证码不正确");
            return "/site/login";
        }

        // 检查用户名和密码
        int expiredSeconds = isRemembered ? REMEMBERED_EXPIRED_SECONDS : DEFAULT_EXPIRED_SECONDS;
        Map<String, Object> map = userService.login(username, password, expiredSeconds);
        // 登录成功啦
        // 重定向到首页
        if(map.containsKey("ticket")) {
            // 实例化一个Cookie用于存储ticket
            Cookie cookie = new Cookie("ticket", (String)map.get("ticket"));
            // 设置存储ticket的cookie在整个项目下有效
            // 这样客户端通过访问各url使用功能时，都会携带cookie中的数据
            cookie.setPath(contextPath);
            // 设置cookie的有效期, 和ticket有效期保持一致
            cookie.setMaxAge(expiredSeconds);
            // 将cookie对象放在服务器response的头
            response.addCookie(cookie);
            return "redirect:/index";
        }
        // 登录失败啦
        else {
            model.addAttribute("usernameMsg", map.get("usernameMsg"));
            model.addAttribute("passwordMsg", map.get("passwordMsg"));
            return "/site/login";
        }
    }

    @LoginRequired
    @RequestMapping(path = "/logout",method = RequestMethod.GET)
    // @RequestMapping(path = "/security-logout",method = RequestMethod.GET)
    public String logout(@CookieValue("ticket") String ticket, HttpServletRequest request, HttpServletResponse response) {
        userService.logOut(ticket);
        // 清除Spring Security的Context
        SecurityContextHolder.clearContext();
        Cookie cookie = new Cookie("JSESSIONID", CommunityUtil.generateUUID());
        response.addCookie(cookie);
        return "redirect:/login";
    }

}
